package com.ghxxzx.dagl.controller;

import cn.gjing.tools.excel.ExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ghxxzx.dagl.entity.*;
import com.ghxxzx.dagl.exceptions.JyException;
import com.ghxxzx.dagl.mapper.*;
import com.ghxxzx.dagl.utils.*;
import com.ghxxzx.dagl.vo.*;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import jxl.write.WritableWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * desc:
 *
 * @author cx316
 * Created by cx316 on 2020-05-29.
 */
@RestController
public class CxtjController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    DaxxMapper daxxMapper;
    @Autowired
    ClxxMapper clxxMapper;
    @Autowired
    DalxMapper dalxMapper;
    @Autowired
    private DaxxWsMapper daxxWsMapper;
    @Autowired
    private WsFlag wsFlag;
    @Autowired
    private GryfKjMapper gryfKjMapper;
    @Autowired
    private LuceneUtiles luceneUtiles;
    @Autowired
    private SyMoreMapper syMoreMapper;

    @RequestMapping("outExcel")
    public ResultEntity outExcel(Integer wdlx, String keyword, String sort, HttpServletResponse response, HttpServletRequest request, Integer startyear, Integer stopyear) {
        // 创建工作表
        response.reset();
        response.setCharacterEncoding("UTF-8");// 设置字符集
        response.setContentType("application/vnd.ms-excel");
        if (stopyear != null && stopyear.intValue() > 4000) {
            stopyear = 4000;
        }
        ServletOutputStream outputStream = null;
        Workbook workbook = null;
        try {
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            Integer lx = hashMap.get(wdlx);
            if (lx == 3) {
                List<DaxxWs> wsList = getDateWs(wdlx, keyword, sort, startyear, stopyear);
                String filename = "文书";
                if (wsList.size() < 1000) {
                    workbook = new XSSFWorkbook();
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
                } else {
                    workbook = new SXSSFWorkbook();
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
                }
                //创建sheet页
                Sheet workbookSheet = workbook.createSheet("文书");
                exportExcelDaxxWs(workbookSheet, wsList);
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
            } else if (lx == 1) {
                List<Daxx> daxxList = getDateKj(wdlx, keyword, sort, startyear, stopyear);
                String filename = "科技";
                if (daxxList.size() < 1000) {
                    workbook = new XSSFWorkbook();
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
                } else {
                    workbook = new SXSSFWorkbook();
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
                }
                //创建sheet页
                Sheet workbookSheet = workbook.createSheet("科技");
                exportExcelDaxx(workbookSheet, daxxList);
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
//                ExcelFactory.createWriter(Daxx.class, response)
//                        .write(daxxList)
//                        .flush();
            } else if (lx == 2) {
                List<GryfKj> gryfKjs = getDataGryfKj(wdlx, keyword, sort, startyear, stopyear);
                String filename = "个人用房";
                if (gryfKjs.size() < 1000) {
                    workbook = new XSSFWorkbook();
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
                } else {
                    workbook = new SXSSFWorkbook();
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
                }
                //创建sheet页
                Sheet workbookSheet = workbook.createSheet("科技-个人用房");
                exportExcelGryf(workbookSheet, gryfKjs);
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void exportExcelDaxxWs(Sheet workbookSheet, List<DaxxWs> daxxWsList) {
        Row row = workbookSheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("档案编号");
        row.createCell(2).setCellValue("文号");
        row.createCell(3).setCellValue("页号");
        row.createCell(4).setCellValue("页数");
        row.createCell(5).setCellValue("总盒号");
        row.createCell(6).setCellValue("档案类型名称");
        row.createCell(7).setCellValue("档案类型di");
        row.createCell(8).setCellValue("单位名称");
        row.createCell(9).setCellValue("文件名称");
        row.createCell(10).setCellValue("时间");
        row.createCell(11).setCellValue("年份");
        row.createCell(12).setCellValue("备注");
        row.createCell(13).setCellValue("录入时间");
        row.createCell(14).setCellValue("登记人");
        for (DaxxWs daxxWs : daxxWsList) {
            int index = 1;
            Row sheetRow = workbookSheet.createRow(workbookSheet.getLastRowNum() + 1);
            sheetRow.createCell(0).setCellValue(daxxWs.getId());
            sheetRow.createCell(1).setCellValue(daxxWs.getDabh());
            sheetRow.createCell(2).setCellValue(daxxWs.getWh());
            sheetRow.createCell(3).setCellValue(daxxWs.getYh());
            sheetRow.createCell(4).setCellValue(daxxWs.getYs());
            sheetRow.createCell(5).setCellValue(daxxWs.getZhh());
            sheetRow.createCell(6).setCellValue(daxxWs.getTypeName());
            sheetRow.createCell(7).setCellValue(daxxWs.getTypeId());
            sheetRow.createCell(8).setCellValue(daxxWs.getDwmc());
            sheetRow.createCell(9).setCellValue(daxxWs.getWjmc());
            sheetRow.createCell(10).setCellValue(daxxWs.getSj());
            sheetRow.createCell(11).setCellValue(daxxWs.getNf());
            sheetRow.createCell(12).setCellValue(daxxWs.getBz());
            sheetRow.createCell(13).setCellValue(DateUtils.getStringDate(daxxWs.getInputtime(), 1));
            sheetRow.createCell(14).setCellValue(daxxWs.getDjr());
            index++;
        }
    }

    public void exportExcelDaxx(Sheet workbookSheet, List<Daxx> daxxList) {
        Row row = workbookSheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("档案类型id");
        row.createCell(2).setCellValue("顺序号");
        row.createCell(3).setCellValue("档案编号");
        row.createCell(4).setCellValue("原盒号");
        row.createCell(5).setCellValue("项目名称");
        row.createCell(6).setCellValue("建设单位");
        row.createCell(7).setCellValue("建设位置");
        row.createCell(8).setCellValue("大厅受理编号");
        row.createCell(9).setCellValue("档案存储位置");
        row.createCell(10).setCellValue("年份");
        row.createCell(11).setCellValue("类型名字");
        row.createCell(12).setCellValue("备注");
        row.createCell(13).setCellValue("其它");
        row.createCell(14).setCellValue("项目方案通过时间");
        row.createCell(15).setCellValue("页数");
        row.createCell(16).setCellValue("超链接");
        row.createCell(17).setCellValue("著录员");
        row.createCell(18).setCellValue("建设项目选址意见书时间");
        row.createCell(19).setCellValue("选址项目名称");
        row.createCell(20).setCellValue("选址用地面积");
        row.createCell(21).setCellValue("建设用地规划许可证时间");
        row.createCell(22).setCellValue("规划项目名称");
        row.createCell(23).setCellValue("规划用地面积");
        row.createCell(24).setCellValue("建设工程规划许可证时间");
        row.createCell(25).setCellValue("工程项目名称");
        row.createCell(26).setCellValue("工程建设规模");
        row.createCell(27).setCellValue("建设工程竣工规划验收合格证时间");
        row.createCell(28).setCellValue("工程竣工项目名称");
        row.createCell(29).setCellValue("工程竣工建设规模");
        row.createCell(30).setCellValue("建设工程施工许可证时间");
        row.createCell(31).setCellValue("建设工程施工许可证编号");
        row.createCell(32).setCellValue("施工工程名称");
        row.createCell(33).setCellValue("施工建设规模");
        row.createCell(34).setCellValue("著录时间");
        row.createCell(35).setCellValue("录入时间");
        row.createCell(36).setCellValue("登记人");
        for (Daxx daxx : daxxList) {
            int index = 1;
            Row sheetRow = workbookSheet.createRow(workbookSheet.getLastRowNum() + 1);
            sheetRow.createCell(0).setCellValue(daxx.getId());
            sheetRow.createCell(1).setCellValue(daxx.getTypeId());
            sheetRow.createCell(2).setCellValue(daxx.getSxh());
            sheetRow.createCell(3).setCellValue(daxx.getDabh());
            sheetRow.createCell(4).setCellValue(daxx.getYhh());
            sheetRow.createCell(5).setCellValue(daxx.getXmmc());
            sheetRow.createCell(6).setCellValue(daxx.getJsdw());
            sheetRow.createCell(7).setCellValue(daxx.getJswz());
            sheetRow.createCell(8).setCellValue(daxx.getDtslbh());
            sheetRow.createCell(9).setCellValue(daxx.getDaccwz());
            sheetRow.createCell(10).setCellValue(daxx.getYear());
            sheetRow.createCell(11).setCellValue(daxx.getTypeName());
            sheetRow.createCell(12).setCellValue(daxx.getBz());
            sheetRow.createCell(13).setCellValue(daxx.getQt());
            sheetRow.createCell(14).setCellValue(daxx.getXmfatgsj());
            sheetRow.createCell(15).setCellValue(daxx.getYs());
            sheetRow.createCell(16).setCellValue(daxx.getClj());
            sheetRow.createCell(17).setCellValue(daxx.getZly());
            sheetRow.createCell(18).setCellValue(daxx.getJsxmxzyjssj());
            sheetRow.createCell(19).setCellValue(daxx.getXzxmmc());
            sheetRow.createCell(20).setCellValue(daxx.getXzydmj());
            sheetRow.createCell(21).setCellValue(daxx.getJsydghxkzsj());
            sheetRow.createCell(22).setCellValue(daxx.getGhxmmc());
            sheetRow.createCell(23).setCellValue(daxx.getGhydmj());
            sheetRow.createCell(24).setCellValue(daxx.getJsgcghxkzsj());
            sheetRow.createCell(25).setCellValue(daxx.getGcxmmc());
            sheetRow.createCell(26).setCellValue(daxx.getGcjsgm());
            sheetRow.createCell(27).setCellValue(daxx.getJsgcjgghyshgsj());
            sheetRow.createCell(28).setCellValue(daxx.getGcjgxmmc());
            sheetRow.createCell(29).setCellValue(daxx.getGcjgjsgm());
            sheetRow.createCell(30).setCellValue(daxx.getJsgcsgxkzsj());
            sheetRow.createCell(31).setCellValue(daxx.getJsgcsgxkzbh());
            sheetRow.createCell(32).setCellValue(daxx.getSggcmc());
            sheetRow.createCell(33).setCellValue(daxx.getSgjsgm());
            sheetRow.createCell(34).setCellValue(daxx.getZlsj());
            sheetRow.createCell(35).setCellValue(DateUtils.getStringDate(daxx.getInputtime(), 1));
            sheetRow.createCell(36).setCellValue(daxx.getDjr());
            index++;
        }
    }

    public void exportExcelGryf(Sheet workbookSheet, List<GryfKj> gryfKjs) {
        Row row = workbookSheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("档案编号");
        row.createCell(2).setCellValue("镇办事处");
        row.createCell(3).setCellValue("村居委会");
        row.createCell(4).setCellValue("申请人");
        row.createCell(5).setCellValue("申请事项");
        row.createCell(6).setCellValue("审批时间");
        row.createCell(7).setCellValue("申请材料");
        row.createCell(8).setCellValue("备注");
        row.createCell(9).setCellValue("起始页码");
        row.createCell(10).setCellValue("终止页码");
        row.createCell(11).setCellValue("总页数");
        row.createCell(12).setCellValue("总盒号");
        row.createCell(13).setCellValue("年份");
        row.createCell(14).setCellValue("档案类型id");
        row.createCell(15).setCellValue("档案类型名称");
        row.createCell(16).setCellValue("录入时间");
        row.createCell(17).setCellValue("登记人");
        for (GryfKj gryfKj : gryfKjs) {
            int index = 1;
            Row sheetRow = workbookSheet.createRow(workbookSheet.getLastRowNum() + 1);
            sheetRow.createCell(0).setCellValue(gryfKj.getId());
            sheetRow.createCell(1).setCellValue(gryfKj.getDabh());
            sheetRow.createCell(2).setCellValue(gryfKj.getTownBsc());
            sheetRow.createCell(3).setCellValue(gryfKj.getVillageJwh());
            sheetRow.createCell(4).setCellValue(gryfKj.getSqr());
            sheetRow.createCell(5).setCellValue(gryfKj.getSqsx());
            sheetRow.createCell(6).setCellValue(gryfKj.getSpsj());
            sheetRow.createCell(7).setCellValue(gryfKj.getSqcl());
            sheetRow.createCell(8).setCellValue(gryfKj.getBz());
            sheetRow.createCell(9).setCellValue(gryfKj.getQsym());
            sheetRow.createCell(10).setCellValue(gryfKj.getZzym());
            sheetRow.createCell(11).setCellValue(gryfKj.getZys());
            sheetRow.createCell(12).setCellValue(gryfKj.getZhh());
            sheetRow.createCell(13).setCellValue(gryfKj.getYear());
            sheetRow.createCell(14).setCellValue(gryfKj.getTypeId());
            sheetRow.createCell(15).setCellValue(gryfKj.getTypeName());
            sheetRow.createCell(16).setCellValue(DateUtils.getStringDate(gryfKj.getInputtime(), 1));
            sheetRow.createCell(17).setCellValue(gryfKj.getDjr());
            index++;
        }
    }

    @RequestMapping("outClxxExcel")
    public ResultEntity outExcel(String[] dabhs, HttpServletResponse response, HttpServletRequest request) {
        // 创建工作表
        response.reset();
        response.setCharacterEncoding("UTF-8");// 设置字符集
        response.setContentType("application/vnd.ms-excel");
        ServletOutputStream outputStream = null;
        Workbook workbook = null;
        try {
            if (dabhs == null || dabhs.length <= 0) {
                return ResultEntity.error("没有可导出的信息");
            }
            QueryWrapper<Clxx> wrapper = new QueryWrapper<>();
            wrapper.in("dabh", dabhs);
            List<Clxx> clxxes = clxxMapper.selectList(wrapper);
            if (clxxes == null) {
                clxxes = new ArrayList<>();
            }
            String filename = "材料信息";
            if (clxxes.size() < 1000) {
                workbook = new XSSFWorkbook();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
            } else {
                workbook = new SXSSFWorkbook();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
            }
            //创建sheet页
            Sheet workbookSheet = workbook.createSheet("材料信息");
            exportExcelClxx(workbookSheet, clxxes);
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void exportExcelClxx(Sheet workbookSheet, List<Clxx> clxxes) {
        Row row = workbookSheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("档案编号");
        row.createCell(2).setCellValue("文件序号");
        row.createCell(3).setCellValue("材料名称");
        row.createCell(4).setCellValue("份数");
        row.createCell(5).setCellValue("起始页码");
        row.createCell(6).setCellValue("终止页码");
        row.createCell(7).setCellValue("页数");
        row.createCell(8).setCellValue("备注");
        row.createCell(9).setCellValue("年份");
        row.createCell(10).setCellValue("类型id");
        row.createCell(11).setCellValue("类型名字");
        row.createCell(12).setCellValue("案卷号，文号");
        row.createCell(13).setCellValue("受理时间");
        for (Clxx clxx : clxxes) {
            Row sheetRow = workbookSheet.createRow(workbookSheet.getLastRowNum() + 1);
            sheetRow.createCell(0).setCellValue(clxx.getId());
            sheetRow.createCell(1).setCellValue(clxx.getDabh());
            sheetRow.createCell(2).setCellValue(clxx.getWjxh());
            sheetRow.createCell(3).setCellValue(clxx.getClmc());
            sheetRow.createCell(5).setCellValue(clxx.getQsym());
            sheetRow.createCell(6).setCellValue(clxx.getZzym());
            if (Optional.ofNullable(clxx.getYs()).isPresent()) {
                sheetRow.createCell(7).setCellValue(clxx.getYs());
            }
            sheetRow.createCell(8).setCellValue(clxx.getBz());
            if (Optional.ofNullable(clxx.getYear()).isPresent()) {
                sheetRow.createCell(9).setCellValue(clxx.getYear());
            }
            sheetRow.createCell(10).setCellValue(clxx.getTypeId());
            sheetRow.createCell(11).setCellValue(clxx.getTypeName());
            sheetRow.createCell(12).setCellValue(clxx.getOtherZh());
            sheetRow.createCell(13).setCellValue(clxx.getSlsj());
            if (Optional.ofNullable(clxx.getFs()).isPresent()) {
                sheetRow.createCell(4).setCellValue(clxx.getFs());
            }
        }
    }

    public List<DaxxWs> getDateWs(Integer wdlx, String keyword, String sort, Integer startyear, Integer stopyear) throws Exception {
        return luceneUtiles.searchDaxxWs(wdlx, keyword, startyear, stopyear, sort);
    }

    public List<Daxx> getDateKj(Integer wdlx, String keyword, String sort, Integer startyear, Integer stopyear) throws Exception {
        return luceneUtiles.searchDaxx(wdlx, keyword, startyear, stopyear, sort);
    }


    public List<GryfKj> getDataGryfKj(Integer wdlx, String keyword, String sort, Integer startyear, Integer stopyear) throws Exception {
        return luceneUtiles.searchGryf(wdlx, keyword, startyear, stopyear, sort);
    }


    //desc降序asc升序 默认降序
    @RequestMapping("dajsOuterCx")
    public ResultEntity dajsOuterCx(Integer[] wdlx, String keyword) throws Exception {
        HashSet<Dalx> list = new HashSet<>();
        ArrayList<Dalx> lxlist = new ArrayList<>();
        List<Dalx> dalxes = dalxMapper.selectListNoRootandWs();
        if (wdlx == null || wdlx.length <= 0) {
            for (Dalx dalx : dalxes) {
                if (!dalx.getCode().equalsIgnoreCase("ws") && !dalx.getCode().equalsIgnoreCase("kj")) {
                    lxlist.add(dalx);
                }
            }
        } else {
            for (Integer integer : wdlx) {
                Dalx dalx = dalxMapper.selectById(integer);
                list.add(dalx);
                diguiLx(integer, list, dalxes);
            }
            for (Dalx dalx : list) {
                if (!dalx.getCode().equalsIgnoreCase("ws") && !dalx.getCode().equalsIgnoreCase("kj")) {
                    lxlist.add(dalx);
                }
            }
        }
        list = null;
        ArrayList<DajsOuterCx> dajsOuterCxes = new ArrayList<>();

        HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
        for (Dalx dalx : lxlist) {
            Integer lx = hashMap.get(dalx.getId());
            Integer id = dalx.getId();
            if (lx == 1) {
                Integer integer = luceneUtiles.searchDaxxOuter(id, keyword, null, null);
                dajsOuterCxes.add(new DajsOuterCx("科技", dalx.getDalxName(), integer, dalx.getId()));

            } else if (lx == 2) {
                Integer integer = luceneUtiles.searchGryfOuter(id, keyword, null, null);
                dajsOuterCxes.add(new DajsOuterCx("科技", dalx.getDalxName(), integer, dalx.getId()));


            } else if (lx == 3) {
                Integer integer = luceneUtiles.searchDaxxWsOuter(id, keyword, null, null);
                dajsOuterCxes.add(new DajsOuterCx("文书", dalx.getDalxName(), integer, dalx.getId()));
            }
        }
        return ResultEntity.ok(dajsOuterCxes);
    }

    public void diguiLx(Integer lx, HashSet<Dalx> lxs, List<Dalx> all) {
        for (Dalx dalx : all) {
            if (dalx.getParentId().intValue() == lx.intValue()) {
                lxs.add(dalx);
                diguiLx(dalx.getId(), lxs, all);
            }
        }
    }

    //desc降序asc升序 默认降序
    @RequestMapping("dajsCx")
    public ResultEntity dajsCx(Integer wdlx, String keyword, String sort, Integer pageSize, Integer pageNum) {
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        try {
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            Integer lx = hashMap.get(wdlx);
            if (lx == 3) {
                luceneUtiles.searchDaxxWsPage(wdlx, keyword, null, null, new PageQuery(pageNum, pageSize), sort, pageResult);
            } else if (lx == 1) {
                luceneUtiles.searchDaxxPage(wdlx, keyword, null, null, new PageQuery(pageNum, pageSize), sort, pageResult);
            } else if (lx == 2) {
                luceneUtiles.searchGryfPage(wdlx, keyword, null, null, new PageQuery(pageNum, pageSize), sort, pageResult);
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
//        PageResult pageResult = PageResultUtils.generatePageResult(page, new PageQuery(pageNum, pageSize));
        return ResultEntity.ok(pageResult);
    }

    public String getIdString(Integer wdlx) {
        Set<Integer> ids = new HashSet<>();
        ids.add(wdlx);
        handlerLxId(ids, wdlx);
        ArrayList<Integer> typeids = new ArrayList<>();
        for (Integer id : ids) {
            typeids.add(id);
        }
        String ss = "";
        for (int i = 0; i < typeids.size(); i++) {
            if (i == (typeids.size() - 1)) {
                ss += typeids.get(i);
            } else {
                ss += typeids.get(i) + ",";
            }
        }
        return ss;
    }

    public ArrayList<Integer> getIdString(Integer[] wdlx) {
        Set<Integer> ids = new HashSet<>();
        for (Integer integer : wdlx) {
            ids.add(integer);
            handlerLxId(ids, integer);
        }
        ArrayList<Integer> typeids = new ArrayList<>();
        for (Integer id : ids) {
            typeids.add(id);
        }

        return typeids;
    }

    @RequestMapping("dajsOuterCx2")
    public ResultEntity dajsOuterCx2(Integer[] wdlx, String keyword, Integer startyear, Integer stopyear) throws Exception {
        HashSet<Dalx> list = new HashSet<>();
        ArrayList<Dalx> lxlist = new ArrayList<>();
        List<Dalx> dalxes = dalxMapper.selectListNoRootandWs();
        if (wdlx == null || wdlx.length <= 0) {
            for (Dalx dalx : dalxes) {
                if (!dalx.getCode().equalsIgnoreCase("ws") && !dalx.getCode().equalsIgnoreCase("kj")) {
                    lxlist.add(dalx);
                }
            }
        } else {
            for (Integer integer : wdlx) {
                Dalx dalx = dalxMapper.selectById(integer);
                list.add(dalx);
                diguiLx(integer, list, dalxes);
            }
            for (Dalx dalx : list) {
                if (!dalx.getCode().equalsIgnoreCase("ws") && !dalx.getCode().equalsIgnoreCase("kj")) {
                    lxlist.add(dalx);
                }
            }
        }
        if (stopyear != null && stopyear.intValue() > 4000) {
            stopyear = 4000;
        }
        list = null;
//        if (startyear == null) {
//            startyear = 0;
//        }
//        if (stopyear == null) {
//            stopyear = 9999;
//        }
        ArrayList<DajsOuterCx> dajsOuterCxes = new ArrayList<>();
        HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
        for (Dalx dalx : lxlist) {
            Integer id = dalx.getId();

            Integer lx = hashMap.get(id);
            if (lx == 1) {
                Integer integer = luceneUtiles.searchDaxxOuter(id, keyword, startyear, stopyear);
                dajsOuterCxes.add(new DajsOuterCx("科技", dalx.getDalxName(), integer, dalx.getId()));

            } else if (lx == 2) {
                Integer integer = luceneUtiles.searchGryfOuter(id, keyword, startyear, stopyear);
                dajsOuterCxes.add(new DajsOuterCx("科技", dalx.getDalxName(), integer, dalx.getId()));

            } else if (lx == 3) {
                Integer integer = luceneUtiles.searchDaxxWsOuter(id, keyword, startyear, stopyear);
                dajsOuterCxes.add(new DajsOuterCx("文书", dalx.getDalxName(), integer, dalx.getId()));
            }
        }
        return ResultEntity.ok(dajsOuterCxes);
    }

    @RequestMapping("dajsCx2")
    public ResultEntity dajsCx2(Integer wdlx, String keyword, String sort, Integer pageSize, Integer pageNum, Integer startyear, Integer stopyear) {
//        if (startyear == null) {
//            startyear = 0;
//        }
//        if (stopyear == null) {
//            stopyear = 9999;
//        }
        if (stopyear != null && stopyear.intValue() > 4000) {
            stopyear = 4000;
        }
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        try {
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            Integer lx = hashMap.get(wdlx);
            if (lx == 3) {
                luceneUtiles.searchDaxxWsPage(wdlx, keyword, startyear, stopyear, new PageQuery(pageNum, pageSize), sort, pageResult);
            } else if (lx == 1) {
                luceneUtiles.searchDaxxPage(wdlx, keyword, startyear, stopyear, new PageQuery(pageNum, pageSize), sort, pageResult);
            } else if (lx == 2) {
                luceneUtiles.searchGryfPage(wdlx, keyword, startyear, stopyear, new PageQuery(pageNum, pageSize), sort, pageResult);
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
//        PageResult pageResult = PageResultUtils.generatePageResult(page, new PageQuery(pageNum, pageSize));
        return ResultEntity.ok(pageResult);
    }

    private void handlerLxId(Set<Integer> ids, Integer wdlx) {
        //第一级子节点
        List<Dalx> dalxes = dalxMapper.findParentIdEq(wdlx);
        if (dalxes == null || dalxes.size() == 0) {
            return;
        }
        Set<Integer> collect = dalxes.stream().map(Dalx::getId).collect(Collectors.toSet());
        ids.addAll(collect);
        for (Integer id : collect) {
            handlerLxId(ids, id);
        }
    }

    @RequestMapping("daylbQuery")
    public ResultEntity daylbQuery(Integer wdlx, Integer startyear, Integer stopyear) {
        Integer pageSize = 10;
        Integer pageNum = 0;
        QueryWrapper<Daxx> daxxQueryWrapper = new QueryWrapper<>();
        QueryWrapper<DaxxWs> wrapper = new QueryWrapper<>();
        QueryWrapper<GryfKj> gryfKjQueryWrapper = new QueryWrapper<>();
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        try {
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            Integer lx = hashMap.get(wdlx);
            if (lx == 3) {
                wrapper.ge("nf", startyear);
                wrapper.le("nf", stopyear);
                if (wdlx != null) {
                    Set<Integer> ids = new HashSet<>();
                    ids.add(wdlx);
                    handlerLxId(ids, wdlx);
                    wrapper.in("type_id", ids);
                }
                wrapper.orderByDesc("id");
                Page<DaxxWs> wsPage = new Page<>(pageNum, pageSize);
                wsPage = daxxWsMapper.selectPage(wsPage, wrapper);
                List<DaxxWs> list = wsPage.getRecords();
                ArrayList<DajsWsVo> dajsWsVos = new ArrayList<>();
                for (DaxxWs daxxWs : list) {
                    dajsWsVos.add(new DajsWsVo(daxxWs.getId(), daxxWs.getId() + "", daxxWs.getDabh(), daxxWs.getWjmc(), daxxWs.getWh(), daxxWs.getDwmc(), daxxWs.getTypeId(), daxxWs.getTypeName(), daxxWs.getNf() + ""));
                }
                pageResult.setData(dajsWsVos);
                pageResult.setTotal(Long.valueOf(wsPage.getTotal()).intValue());
            } else if (lx == 1) {
                daxxQueryWrapper.ge("year", startyear);
                daxxQueryWrapper.le("year", stopyear);
                if (wdlx != null) {
                    Set<Integer> ids = new HashSet<>();
                    ids.add(wdlx);
                    handlerLxId(ids, wdlx);
                    daxxQueryWrapper.in("type_id", ids);
                }
                daxxQueryWrapper.orderByDesc("sxh");
                Page<Daxx> daxxPage = new Page<>(pageNum, pageSize);
                daxxPage = daxxMapper.selectPage(daxxPage, daxxQueryWrapper);
                pageResult.setData(daxxPage.getRecords());
                pageResult.setTotal(Long.valueOf(daxxPage.getTotal()).intValue());
            } else if (lx == 2) {
                gryfKjQueryWrapper.ge("year", startyear);
                gryfKjQueryWrapper.le("year", stopyear);
                if (wdlx != null) {
                    Set<Integer> ids = new HashSet<>();
                    ids.add(wdlx);
                    handlerLxId(ids, wdlx);
                    gryfKjQueryWrapper.in("type_id", ids);
                }
                gryfKjQueryWrapper.orderByDesc("id");
                Page<GryfKj> daxxPage = new Page<>(pageNum, pageSize);
                daxxPage = gryfKjMapper.selectPage(daxxPage, gryfKjQueryWrapper);
                pageResult.setData(daxxPage.getRecords());
                pageResult.setTotal(Long.valueOf(daxxPage.getTotal()).intValue());
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
//        PageResult pageResult = PageResultUtils.generatePageResult(page, new PageQuery(pageNum, pageSize));
        return ResultEntity.ok(pageResult);
    }


    @RequestMapping("newestDa")
    public ResultEntity newestDa(PageQuery pageQuery, String sort) {
        try {
            QueryWrapper<SyMore> wrapper = new QueryWrapper<>();
            if (sort.equalsIgnoreCase("desc")) {
                wrapper.orderByDesc("input_time");
            } else {
                wrapper.orderByAsc("input_time");
            }
            Page page = PageResultUtils.getPage(pageQuery, SyMore.class);
            page = syMoreMapper.selectPage(page, wrapper);
            PageResult pageResult = PageResultUtils.generatePageResult(page, pageQuery);
            return ResultEntity.ok(pageResult);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }


    public ArrayList<Integer> getDaxxTypeId() {
        List<Dalx> allfirst = dalxMapper.findAllfirst();
        ArrayList<Dalx> all = new ArrayList<>();
        HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
        for (Dalx dalx : allfirst) {
            Integer lx = hashMap.get(dalx.getId());
            if (lx == 1) {
                if ((!dalx.getCode().equalsIgnoreCase("ws")) && (!dalx.getCode().equalsIgnoreCase("kj"))) {
                    all.add(dalx);
                }
            }
        }
        allfirst = null;
        ArrayList<Integer> integers = new ArrayList<>();
        for (Dalx dalx : all) {
            integers.add(dalx.getId());
        }
        return integers;
    }

    public ArrayList<Integer> getGryfTypeId() {
        List<Dalx> allfirst = dalxMapper.findAllfirst();
        ArrayList<Dalx> all = new ArrayList<>();
        HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
        for (Dalx dalx : allfirst) {
            Integer lx = hashMap.get(dalx.getId());
            if (lx == 2) {
                if ((!dalx.getCode().equalsIgnoreCase("ws")) && (!dalx.getCode().equalsIgnoreCase("kj"))) {
                    all.add(dalx);
                }
            }
        }
        allfirst = null;
        ArrayList<Integer> integers = new ArrayList<>();
        for (Dalx dalx : all) {
            integers.add(dalx.getId());
        }
        return integers;
    }

    public ArrayList<Integer> getDaxxWsTypeId() {
        List<Dalx> allfirst = dalxMapper.findAllfirstWs();
        ArrayList<Dalx> all = new ArrayList<>();
        HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
        for (Dalx dalx : allfirst) {
            Integer lx = hashMap.get(dalx.getId());
            if (lx == 3) {
                if ((!dalx.getCode().equalsIgnoreCase("ws")) && (!dalx.getCode().equalsIgnoreCase("kj"))) {
                    all.add(dalx);
                }
            }
        }
        allfirst = null;
        ArrayList<Integer> integers = new ArrayList<>();
        for (Dalx dalx : all) {
            integers.add(dalx.getId());
        }
        return integers;
    }

    @RequestMapping("queryClxxAll")
    public ResultEntity newestDa(String keyword, String sort, Integer pageSize, Integer pageNum, Integer[] lxs, String[] dabhs) {
        try {
            if (keyword != null && keyword.trim().equals("")) {
                keyword = null;
            }
            PageResult pageResult = new PageResult();
            pageResult.setPageNum(pageNum);
            pageResult.setPageSize(pageSize);
            if (dabhs != null && dabhs.length > 0) {
                Page page = PageResultUtils.getPage(new PageQuery(pageNum, pageSize), Clxx.class);
                QueryWrapper<Clxx> wrapper = new QueryWrapper<>();
                wrapper.in("dabh", dabhs);
                page = clxxMapper.selectPage(page, wrapper);
                PageResult result = PageResultUtils.generatePageResult(page, new PageQuery(pageNum, pageSize));
//                luceneUtiles.searchClxxDabhs(strings, sort, pageResult, new PageQuery(pageNum, pageSize));
                return ResultEntity.ok(result);
            } else {
                HashSet<Dalx> list = new HashSet<>();
                ArrayList<Dalx> lxlist = new ArrayList<>();
                List<Dalx> dalxes = dalxMapper.selectListNoRootandWs();
                if (lxs == null || lxs.length <= 0) {
                    for (Dalx dalx : dalxes) {
                        if (!dalx.getCode().equalsIgnoreCase("ws") && !dalx.getCode().equalsIgnoreCase("kj")) {
                            lxlist.add(dalx);
                        }
                    }
                } else {
                    for (Integer integer : lxs) {
                        Dalx dalx = dalxMapper.selectById(integer);
                        list.add(dalx);
                        diguiLx(integer, list, dalxes);
                    }
                    for (Dalx dalx : list) {
                        if (!dalx.getCode().equalsIgnoreCase("ws") && !dalx.getCode().equalsIgnoreCase("kj")) {
                            lxlist.add(dalx);
                        }
                    }
                }
                ArrayList<Integer> integers = new ArrayList<>();
                for (Dalx dalx : lxlist) {
                    integers.add(dalx.getId());
                }
                luceneUtiles.searchClxx(integers, keyword, sort, pageResult, new PageQuery(pageNum, pageSize));
                return ResultEntity.ok(pageResult);

            }

        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping("queryClxxById")
    public ResultEntity queryClxxById(Integer id) {
        try {
            Clxx clxx = clxxMapper.selectById(id);
            List<Clxx> clxxes = clxxMapper.selectByDabh(clxx.getDabh());
            return ResultEntity.ok(new ClxxJsVo(clxx, clxxes));
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping("queryYlbFlag")
    public ResultEntity queryYlbFlag(HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            int flag = 0;
            if ((user.getRoleId().intValue() == 1) || (user.getRoleId().intValue() == 2)) {
                flag = 2;
            } else {
                flag = 1;
            }
            return ResultEntity.ok(flag);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping("queryDazl")
    public ResultEntity queryDazl() {
        try {
            List<Dalx> dalxList = dalxMapper.selectListNoRootandWs();
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            QueryWrapper<Daxx> daxxQueryWrapper = new QueryWrapper<>();
            QueryWrapper<DaxxWs> daxxWsQueryWrapper = new QueryWrapper<>();
            QueryWrapper<GryfKj> gryfKjQueryWrapper = new QueryWrapper<>();
            ArrayList<LxZl> list = new ArrayList<>();
            for (Dalx dalx : dalxList) {
                Integer integer = hashMap.get(dalx.getId());
                if (integer == 1) {
                    daxxQueryWrapper.eq("type_id", dalx.getId());
                    Integer count = daxxMapper.selectCount(daxxQueryWrapper);
                    list.add(new LxZl(dalx.getDalxName(), count.longValue()));
                    daxxQueryWrapper.clear();
                } else if (integer == 2) {
                    gryfKjQueryWrapper.eq("type_id", dalx.getId());
                    Integer count = gryfKjMapper.selectCount(gryfKjQueryWrapper);
                    list.add(new LxZl(dalx.getDalxName(), count.longValue()));
                    gryfKjQueryWrapper.clear();
                } else if (integer == 3) {
                    daxxWsQueryWrapper.eq("type_id", dalx.getId());
                    Integer count = daxxWsMapper.selectCount(daxxWsQueryWrapper);
                    list.add(new LxZl(dalx.getDalxName(), count.longValue()));
                    daxxWsQueryWrapper.clear();
                }
            }
            return ResultEntity.ok(list);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping("queryKjDazl")
    public ResultEntity queryKjDazl() {
        try {
            List<Dalx> dalxList = dalxMapper.selectListNoRootandWs();
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            QueryWrapper<Daxx> daxxQueryWrapper = new QueryWrapper<>();
            QueryWrapper<GryfKj> gryfKjQueryWrapper = new QueryWrapper<>();
            ArrayList<LxZl> list = new ArrayList<>();
            for (Dalx dalx : dalxList) {
                Integer integer = hashMap.get(dalx.getId());
                if (integer == 1) {
                    daxxQueryWrapper.eq("type_id", dalx.getId());
                    Integer count = daxxMapper.selectCount(daxxQueryWrapper);
                    list.add(new LxZl(dalx.getDalxName(), count.longValue()));
                    daxxQueryWrapper.clear();
                } else if (integer == 2) {
                    gryfKjQueryWrapper.eq("type_id", dalx.getId());
                    Integer count = gryfKjMapper.selectCount(gryfKjQueryWrapper);
                    list.add(new LxZl(dalx.getDalxName(), count.longValue()));
                    gryfKjQueryWrapper.clear();
                }
            }
            return ResultEntity.ok(list);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping("queryWsDazl")
    public ResultEntity queryWsDazl() {
        try {
            List<Dalx> dalxList = dalxMapper.selectListNoRootandWs();
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            QueryWrapper<DaxxWs> daxxWsQueryWrapper = new QueryWrapper<>();
            ArrayList<LxZl> list = new ArrayList<>();
            for (Dalx dalx : dalxList) {
                Integer integer = hashMap.get(dalx.getId());
                if (integer == 3) {
                    daxxWsQueryWrapper.eq("type_id", dalx.getId());
                    Integer count = daxxWsMapper.selectCount(daxxWsQueryWrapper);
                    list.add(new LxZl(dalx.getDalxName(), count.longValue()));
                    daxxWsQueryWrapper.clear();
                }
            }
            return ResultEntity.ok(list);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
}
